import { apiUserGetLoginUser, purtbSelectPurtb, purtcDelPurtc, purtcList, purtcPurchaseDetail } from '@/api/url/salesOrderManagement';
import router from '@/router';
import { EFTimeFormatConversion, formatDate, isNullPm, spaceTime } from '@/utils/baseMethods';
import { PURTBCHANGE } from '@/utils/EFCODE';
import { reactive, watch } from 'vue';
import notification from '@arco-design/web-vue/es/notification';
import XEClipboard from 'xe-clipboard';
import { VXETable } from 'vxe-table';
import { dayjs } from '@arco-design/web-vue/es/_utils/date';

export default function importConfig() {
  const base = reactive<any>({
    pagination: {
      total: 100,
      current: 1,
      pageSize: 10,
    },
    tabelList: null,
    checkFrom: {
      type: null,
      id: null,
      supplier: null,
      purchaseDate: null,
      taxType: null,
      remark: null,
    },
    ggDomas: [],
    getOmnList: [],
    tableRef: null,
    visible: false,
    desData: null,
    defaultSelecteRowKeys: [],
    tabelValue: false,
    searchBar: '隐藏搜索',
    formHeaderVisible: true,
    tableHeight: 'calc(100vh - 420px)',
  });

  const init = () => {
    base.tabelValue = false;
    getTable();
    apiUserGetLoginUser('').then((reb: any) => {
      if (reb.code == '200') {
        const steamOpmc = {
          userNo: reb.data.ma001,
          userName: reb.data.ma002,
        };
        localStorage.setItem('POOMPMO', JSON.stringify(steamOpmc));
      }
    });
  };

  /**
   * @exports defaultValueWriteBack 数据回写绑定
   */
  const defaultValueWriteBack = () => {
    // const steam: any = localStorage.getItem('BLISOK')
    // base.defaultSelecteRowKeys = []
    // if (!isNullPm(steam)) {
    //   JSON.parse(steam).map((reb: any) => {
    //     console.log(reb)
    //     reb?.getOmnList.map((res: any) => {
    //       base.defaultSelecteRowKeys.push(res.requisitionType + res.requisitionNo + res.requisitionNumber)
    //       base.getOmnList.push(res)
    //     })
    //   })
    // }
    base.tabelValue = true;
  };

  const getTable = () => {
    const obj = {
      size: base.pagination.pageSize,
      current: base.pagination.current,
    };

    const relt = base.checkFrom;
    const steamDom = {};
    if (relt.purchaseDate) {
      relt.purchaseDate = dayjs(relt.purchaseDate).format('YYYYMMDD');
    }

    Object.keys(relt).map((res: any) => {
      if (!isNullPm(relt[res])) {
        steamDom[res] = relt[res];
      }
    });
    purtcList(obj, steamDom).then((res: any) => {
      if (res.code === '200') {
        base.tabelList = res.data.list;
        base.pagination.total = res.data.total;
        defaultValueWriteBack();
      }
    });
  };

  const handlePageChange = (page: number) => {
    base.pagination.current = page;
    init();
  };

  const handlePageSizeChange = (pageSize: number) => {
    base.pagination.pageSize = pageSize;
    init();
  };

  const selectChange = (param) => {
    base.getOmnList = [];
    param.forEach((res: any) => {
      base.getOmnList.push(base.tabelList[res]);
    });
  };

  const purchaseOrderGeneration = (): any => {
    // router.push({
    //   path: '/purchaseOrderAdd',
    //   query: {
    //     featureData: JSON.stringify(base.featureData),
    //   },
    // });
  };

  /**
   * @exports selectAllChangeEvent  列表全选or全不选
   * @param param
   */
  const selectAllChangeEvent = () => {
    base.getOmnList = statusScreening(base.tableRef.getCheckboxRecords());

    dataProcessing();
  };

  /**
   * @exports selectChangeEvent 列表单选or多选
   * @param param
   */
  const selectChangeEvent = () => {
    base.getOmnList = statusScreening(base.tableRef.getCheckboxRecords());
    dataProcessing();
  };

  /**
   * @exports dataProcessing 数据处理,默认规定,如果只换分页，则不重置数据，如果换了条数，则重置数据
   */
  const dataProcessing = () => {
    const steam: any = localStorage.getItem('BLISOK');
    if (isNullPm(steam)) {
      const steamDom: any = [
        {
          current: base.pagination.current,
          pageSize: base.pagination.pageSize,
          getOmnList: base.getOmnList,
        },
      ];
      localStorage.setItem('BLISOK', JSON.stringify(steamDom));
    } else {
      let steamDom = JSON.parse(steam);
      let subscript = false;
      let identifier = false;
      let numberInd = 0;
      steamDom.map((res: any, index: any) => {
        if (res.pageSize != base.pagination.pageSize) {
          subscript = true;
        }
        if (res.current == base.pagination.current) {
          identifier = true;
          numberInd = index;
        }
      });
      if (subscript) {
        steamDom = [];
        steamDom.push({
          current: base.pagination.current,
          pageSize: base.pagination.pageSize,
          getOmnList: base.getOmnList,
        });
      } else {
        if (!identifier)
          steamDom.push({
            current: base.pagination.current,
            pageSize: base.pagination.pageSize,
            getOmnList: base.getOmnList,
          });
        else steamDom[numberInd].getOmnList = base.getOmnList;
      }
      localStorage.setItem('BLISOK', JSON.stringify(steamDom));
    }
  };

  /**
   * @exports statusScreening 将已完成的数据筛选掉
   */
  const statusScreening = (param) => {
    const steam: any = [];
    param.map((res: any) => {
      if (res.status != '已完成') {
        steam.push(res);
      }
    });
    return steam;
  };

  // watch(() => base.pagination, () => {
  //   init()
  // }, {
  //   deep: true
  // })

  /**
   * @exports menuConfig 表单配置器
   */
  const menuConfig = reactive<any>({
    className: 'my-menus',
    body: {
      options: [
        [{ code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' }],
        [{ code: 'viewDetails', name: '查看详情', prefixIcon: 'vxe-icon-success-circle-fill', className: 'my-copy-item' }],
      ],
    },
  });
  /**
   * @exports contextMenuBodyClickEvent 表单操作格式
   * @param param0
   */
  const contextMenuBodyClickEvent = ({ menu, row, column }) => {
    switch (menu.code) {
      case 'viewDetails':
        viewDetails(row);
        break;
      case 'copy':
        // 示例
        if (row && column) {
          console.log(row, column);
          if (XEClipboard.copy(row[column.field])) {
            VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
          }
        }
        break;
      default:
        console.log(`点击了 ${menu.name} 选项`, row, column, row[column.field]);
    }
  };

  /**
   * @exports stateGenerationMethod 状态生成工具
   */
  const stateGenerationMethod = (param) => {
    const bindTime = formatDate(new Date(), 'yyyy-MM-dd');
    if (param.number <= param.purchasedQuantity) return '已完成';
    else if (spaceTime(bindTime, EFTimeFormatConversion(param.requirementDate)) < 0) return '异常订单';
    else if (spaceTime(bindTime, EFTimeFormatConversion(param.requirementDate)) < 7) return '临近日期';
    else if (param.purchasedQuantity > 0 && param.number > param.purchasedQuantity) return '待处理完成';
    else return '待处理';
  };

  /**
   * @exports purchaseRequisitionDetails 请购单详情
   */
  const purchaseRequisitionDetails = (param) => {
    const steam = {
      tb001: param.requisitionType,
      tb002: param.requisitionNo,
      tb003: param.requisitionNumber,
    };
    purtbSelectPurtb(steam).then((res: any) => {
      if (res.code == '200') {
        base.desData = PURTBCHANGE(res.data);
        base.visible = true;
      }
    });
  };

  /**
   * @exports resetSelectItem 重置选择项目
   */
  const resetSelectItem = () => {
    localStorage.removeItem('BLISOK');
    init();
  };

  /**
   * @exports deleteOption
   */
  const deleteOption = (param) => {
    purtcDelPurtc(`?TC001=${param.type}&TC002=${param.id}  `).then((res: any) => {
      if (res.code == 200) {
        init();
        notification.success('删除成功');
      }
    });
  };

  /**
   * @exports viewDetails 查看采购单详情
   */
  const viewDetails = (param) => {
    router.push({ path: '/purchaseOrderDetails', query: { type: param.type, id: param.id } });
  };

  /**
   * @exports printDetails 打印
   */
  const printDetails = (param, steam) => {
    router.push({ path: '/test', query: { type: param.type, id: param.id, steam: steam } });
  };

  return {
    handlePageChange,
    handlePageSizeChange,
    base,
    init,
    selectChange,
    purchaseOrderGeneration,
    selectAllChangeEvent,
    selectChangeEvent,
    menuConfig,
    contextMenuBodyClickEvent,
    stateGenerationMethod,
    resetSelectItem,
    deleteOption,
    viewDetails,
    printDetails,
  };
}
